<!--
  @文件名： updatePasswordDialog
  @Author: lina
  @Date: 2023-11-22 15:03
  @描述：修改密码弹窗
-->
<template>
  <el-dialog v-model="state.dialogVisible" :destroy-on-close="true" :title="$t('LG.baseModel.changePassword')" :width="getSizeOnWidthPage(500)" @closed="switchDialog(false)">
    <el-form :model="state.pwdform" :rules="pwdformRules" ref="pwdformRef" label-width="auto">
      <el-form-item :label="$t('LG.baseModel.oldPassword')" prop="oldPwd">
        <el-input v-model="state.pwdform.oldPwd" type="text" :placeholder="$t('LG.baseModel.pleaseEnterOldPassword')" style="text-security: disc; -webkit-text-security: disc"></el-input>
      </el-form-item>
      <el-form-item :label="$t('LG.baseModel.newPassword')" prop="newPwd">
        <el-input v-model="state.pwdform.newPwd" type="text" :placeholder="$t('LG.baseModel.pleaseEnterNewPassword')" style="text-security: disc; -webkit-text-security: disc"></el-input>
      </el-form-item>
      <el-form-item :label="$t('LG.baseModel.confirmPassword')" prop="repeatPwd">
        <el-input v-model="state.pwdform.repeatPwd" type="text" :placeholder="$t('LG.baseModel.PleaseEnterYourNewPasswordAgain')" style="text-security: disc; -webkit-text-security: disc"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="foot">
        <el-button @click="state.dialogVisible = false" size="default">{{ $t('LG.baseModel.cancel') }}</el-button>
        <el-button type="primary" @click="confirmUpdate" size="default">{{ $t('LG.baseModel.confirm') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import { getSizeOnWidthPage } from '@/units/domUnits.ts'
  import { msgError, msgWarning } from '@/units/messageUnits.ts'
  import { useI18n } from 'vue-i18n'
  import { changePwdApi } from '@/api/userApi'
  import { userInfo } from '@/store/userInfo.ts'
  const { t } = useI18n()
  const userInfoStore = userInfo()

  const pwdformRef = ref()
  const pwdformRules = computed(() => {
    return {
      oldPwd: [{ required: true, message: t('LG.baseModel.pleaseEnterOldPassword'), trigger: 'blur' }],
      newPwd: [
        { required: true, message: t('LG.baseModel.pleaseEnterNewPassword'), trigger: 'blur' },
        { max: 20, message: t('LG.baseModel.MaximumTwentyDigits'), trigger: 'blur' },
        { min: 6, message: t('LG.baseModel.AtLeastSixDigits'), trigger: 'blur' },
        {
          validator: (rule: any, value: string, callback: any) => {
            if (value) {
              if (/[\u4E00-\u9FA5]/g.test(value)) {
                callback(new Error(t('LG.baseModel.CannotContainChinese')))
              } else if (/[\s]/g.test(value)) {
                callback(new Error(t('LG.baseModel.CannotContainSpaces')))
              } else {
                callback()
              }
            }
            callback()
          },
          trigger: 'blur',
        },
        {
          validator: (rule: any, value: string, callback: any) => {
            if (state.pwdform.repeatPwd !== '') {
              if (value !== state.pwdform.repeatPwd) {
                callback(new Error(t('LG.baseModel.TwoPasswordAreInconsistent')))
              }
            }
            callback()
          },
          trigger: 'change',
        },
      ],
      repeatPwd: [
        { required: true, message: t('LG.baseModel.PleaseEnterYourNewPasswordAgain'), trigger: 'blur' },
        {
          validator: (rule: any, value: string, callback: any) => {
            if (state.pwdform.newPwd !== '') {
              if (value !== state.pwdform.newPwd) {
                callback(new Error(t('LG.baseModel.TwoPasswordAreInconsistent')))
              }
            }
            callback()
          },
          trigger: 'change',
        },
      ],
    }
  })
  const state = reactive<any>({
    dialogVisible: false,
    pwdform: {
      oldPwd: '',
      newPwd: '',
      repeatPwd: '',
    },
  })

  // 切换
  const switchDialog = (type: boolean, data?: any) => {
    state.dialogVisible = type
    if (type) {
      if (data) {
        state.pwdform.oldPwd = data.oldPwd
        state.pwdform.newPwd = data.newPwd
        state.pwdform.repeatPwd = data.repeatPwd
      } else {
        msgWarning(t(`LG.baseModel.noDataInformation`))
      }
    } else {
      state.pwdform.oldPwd = ''
      state.pwdform.newPwd = ''
      state.pwdform.repeatPwd = ''
    }
  }
  // 确认修改
  const confirmUpdate = async (): Promise<void> => {
    let userId: String
    pwdformRef.value?.validate((val: any) => {
      if (val) {
        changePwdApi({
          currentUserId: '',
          newPwd: state.pwdform.newPwd,
          oldPwd: state.pwdform.oldPwd,
          userId,
        })
          .then((res: any) => {
            if (res.code == 200) {
              state.dialogVisible = false
              ElMessageBox.confirm(t('LG.baseModel.PasswordChangedSuccessfully'), t('LG.baseModel.PleaseLoginAgain'), { type: 'success' })
                .then(async () => {
                  void userInfoStore.userLogout().then(() => {
                    void router.replace('/')
                  })
                })
                .catch(() => {
                  void userInfoStore.userLogout().then(() => {
                    void router.replace('/')
                  })
                })
            } else {
              msgError(res.msg || t(`LG.baseModel.requestInterfaceFailed`))
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    })
  }

  defineExpose({
    switchDialog,
  })
</script>

<style scoped lang="scss"></style>
